package kr.hkit.powerjava.chapter25;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class CalculatorEx extends JFrame implements ActionListener{

	private JPanel contentPane;
	private CalPanel panel;
	private JPanel panel_1;
	private JButton btnClear;
	private JButton btnCal;
	
	public static void main(String[]args){
		EventQueue.invokeLater(new Runnable(){
			public void run(){
				try{
					CalculatorEx frame = new CalculatorEx();
					frame.setVisible(true);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
	}
	
	public CalculatorEx(){
		initialize();
	}
	public void initialize(){
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100,100,450,300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5,5,5,5));
		contentPane.setLayout(new BorderLayout(0,0));
		setContentPane(contentPane);
		
		panel = new CalPanel();
		contentPane.add(panel, BorderLayout.CENTER);
		panel_1 = new JPanel();
		contentPane.add(panel_1, BorderLayout.SOUTH);
		
		btnCal = new JButton("계산");
		btnCal.addActionListener(this);
		panel_1.add(btnCal);
		
		btnClear = new JButton("Clear");
		btnClear.addActionListener(this);
		panel_1.add(btnClear);
		
		pack();
		
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getActionCommand().equals("계산")){
			int left = 0;
			int right= 0;
			
			try{
				left = Integer.parseInt(panel.getTfLeft().trim());			
			}catch(NumberFormatException err){
			JOptionPane.showMessageDialog(this, "숫자만 가능합니다.");
			panel.setTfRight("");
			}
			try{
				right = Integer.parseInt(panel.getTfRight().trim());
			}catch(NumberFormatException err){
				JOptionPane.showMessageDialog(this, "숫자만 가능합니다.");
				panel.setTfRight("");
			}
			
			panel.setTfResult(left*right+"");
			
		}else {
			panel.setTfLeft("");
			panel.setTfResult("");
			panel.setTfRight("");
		}
	}
}
